#!usr/bin/env python
# coding=utf-8

from google.appengine.ext.webapp import RequestHandler
from model.model import PassbyItem, Comment
from model import get_member_by_id
from api import WriteJson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext import db
from google.appengine.api.datastore_types import GeoPt
from api.oauthRequest import BaseSourceOauthRequest
from google.appengine.api import datastore_errors, memcache
from config import ONE_MONTH

class CreatItemHandler(BaseSourceOauthRequest):
    def postHandler(self,member):
        content = self.request.get('content')
        try:
            location = GeoPt(self.request.get("location"))
        except datastore_errors.BadValueError, err:
            WriteJson(self, {"result":False,"message":err.message}, "normalResult.json")
            return
        if len(content)>0:
            try:
                template_values = {}
                item = PassbyItem()
                item.content = content
                item.location = location
                item.member = member
                item.put()
                memcache.set("PassByItem::"+str(member.key().id), item, ONE_MONTH)
                template_values["item"] = item
                WriteJson(self,template_values,'passbyitem.json')
            except:
                WriteJson(self, {'result':False,'message':'invalid location'}, 'normalResult.json')
        else:
            WriteJson(self, {'result':False,'message':'content can not be null'}, 'normalResult.json')
            
class GetItemsByPointHandler(RequestHandler):
    def Get(self):
        #TO-DO
        pass
    
class GetItemsByUidHandler(BaseSourceOauthRequest):
    def postHandler(self,member):
        memb = get_member_by_id(int(self.request.get('uid')))
        if memb is not False:
            page = 1
            if self.request.get('page'):
                page = self.request.get('page')
            count = 20
            if self.request.get("count"):
                count = int(self.request.get('count'))
                if count > 100 or count < 1:
                    count = 20
            q = db.GqlQuery('SELECT * FROM PassbyItem WHERE member = :1',memb)
            templateData = {}
            if q.count() >= count:
                if q.count >= count*(page-1):
                    templateData['items'] = q.fetch(count, count*(page-1))
                else:
                    templateData['items'] = q.fetch(count, q.count - count - 1)
            else:
                templateData['items'] = q.fetch(count)
            WriteJson(self, templateData, 'passbyitems.json')
        else:
            WriteJson(self, {"result":False,"message":"member not found"}, "normalError.json")
    
class GetItemHandler(BaseSourceOauthRequest):
    def getHandler(self,member):
        id = self.request.get('item_id')
        q = db.GqlQuery('SELECT * FROM PassbyItem WHERE item_id = :1',id)
        if q.count == 1:
            templateData = {}
            templateData['item'] = q[0]
            WriteJson(self,templateData,'passbyitem.json')
        else:
            WriteJson(self, {"result":False,"message":"item not found"}, "normalError.json")
    
class CommitHandler(BaseSourceOauthRequest):
    def getHandler(self,member):
        id = self.request.get('id')
        q = PassbyItem.get_by_id(id)
        if q.count() == 1:
            item = q[0]
            comment = Comment()
            comment.item = item
            comment.content = self.request.get('content')
            comment.comment_id = item.comments
            item.comments += 1
            item.put()
            comment.put()
            templateData = {}
            templateData['item'] = comment
            WriteJson(self,templateData,'comment.json')
        else :
            WriteJson(self, {"result":False,"message":"item not found"}, "normalError.json")
    
class DeleteItemHandler(BaseSourceOauthRequest):
    def getHandler(self,member):
        k = self.request.get('key')
        key = db.Key(k)
        q = db.GqlQuery('SELECT __key__ FROM PassbyItem WHERE __key__ = :1',key)
        if q.count == 1:
            templateData = {}
            templateData['item'] = q[0]
            WriteJson(self,templateData,'passbyitem.json')
        else :
            self.response.set_status(400,'item not found')

def main():
    application = webapp.WSGIApplication([('/api/luckyItem/creatItem',CreatItemHandler),
                                          ('/api/luckyItem/getItemsByPoint',GetItemsByPointHandler),
                                          ('/api/luckyItem/getitemsbyuid',GetItemsByUidHandler),
                                          ('/api/luckyItem/getItem',GetItemHandler),
                                          ('/api/luckyItem/deleteItem',DeleteItemHandler),
                                          ('/api/luckyItem/comment',CommitHandler)],
                                         debug=True) 
    util.run_wsgi_app(application)
    
if __name__ == '__main__':
    main()
